package com.blb.thread.homework;

/**
 * 编写线程死锁案例
 * 两个线程分别持有对方的锁，又需要对方持有的锁
 * 解决死锁：
 * 1. 避免写同步代码块嵌套代码
 * 2. 使用通过同步锁，可以限定时间，自动释放锁
 */
public class DeadLockDemo {

    //两个锁对象
    private Object lock1 = new Object();
    private Object lock2 = new Object();

    public void function1(){
        synchronized (lock1){
            //线程持有一把锁，需要另一把锁
            System.out.println(Thread.currentThread().getName()+"持有lock1，需要lock2");
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (lock2){
                System.out.println(Thread.currentThread().getName()+"正常执行完");
            }
        }
    }

    public void function2(){
        synchronized (lock2){
            //线程持有一把锁，需要另一把锁
            System.out.println(Thread.currentThread().getName()+"持有lock2，需要lock1");
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (lock1){
                System.out.println(Thread.currentThread().getName()+"正常执行完");
            }
        }
    }

    public static void main(String[] args) {
        DeadLockDemo deadLockDemo = new DeadLockDemo();
        new Thread(() -> {
            deadLockDemo.function1();
        }).start();
        new Thread(() -> {
            deadLockDemo.function2();
        }).start();
    }
}
